package dba.example.controllers

import org.springframework.data.domain.Sort
import dba.example.entities.Account
import org.springframework.web.bind.annotation.{ModelAttribute, RequestParam, RequestMapping, RequestMethod}
import dba.example.repos.{CompanyRepository, AccountRepository}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.ui.ModelMap
import javax.validation.Valid
import org.springframework.validation.BindingResult
import org.springframework.stereotype.Controller
import dba.example.common.DefaultPageable

@Controller
@RequestMapping(Array("/account"))
class AccountController @Autowired() (repo: AccountRepository, cRepo: CompanyRepository) {

  @RequestMapping(value = Array("/list"))
  def list(model: ModelMap, @RequestParam(defaultValue = "0") pageNo: Integer,
           @RequestParam(defaultValue = "nameSort") sortColumn: String,
           @RequestParam(defaultValue = "ASC") sortDirection: Sort.Direction) = {
    model.addAttribute("page", repo.findAll(new DefaultPageable(pageNo, 10, 0, new Sort(sortDirection, sortColumn))))
    model.addAttribute("sortColumn", sortColumn)
    model.addAttribute("sortDirection", sortDirection)
    "accountList"
  }

  @RequestMapping(value = Array("/view"))
  def view(@RequestParam id: Integer, model: ModelMap) = {
    model.addAttribute("account", repo.findOne(id))
    "accountView"
  }

  @RequestMapping(value = Array("/edit"))
  def edit(@RequestParam id: Integer, model: ModelMap) = {
    model.addAttribute("account", repo.findOne(id))
    model.addAttribute("companies", cRepo.findAll)
    "accountEdit"
  }

  @RequestMapping(value = Array("/add"))
  def add(model: ModelMap) = {
    model.addAttribute("account", new Account)
    model.addAttribute("companies", cRepo.findAll)
    "accountEdit"
  }

  @RequestMapping(value = Array("/save"), method = Array(RequestMethod.POST))
  def addContact(@Valid @ModelAttribute("account") account: Account, result: BindingResult): String = {
    if (result.hasErrors) {
      "companyEdit"
    }
    repo.saveAndFlush(account)
    "redirect:list"
  }

}

